﻿#region
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Windows.Forms;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;

#endregion

namespace TumblrDownloader
{
    public partial class PageLoadingForm : Form
    {
        private PageLoadingForm()
        {
            InitializeComponent();
        }

        public PageLoadingForm(string tumblrId)
            : this()
        {
            _tumblrId = tumblrId;
            Srcs = new List<string>();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (DesignMode)
                return;

            bgwPageLoader.RunWorkerAsync(_tumblrId);
        }

        private readonly string _tumblrId;

        public List<string> Srcs { get; private set; }

        private void bgwPageLoader_DoWork(object sender, DoWorkEventArgs e)
        {
            string tumblrId = (string) e.Argument;

            WebClient web = new WebClient();

            int page = 1;

            while (true)
            {
                string message = string.Format("{0:N0} 페이지를 읽고 있습니다.", page);
                bgwPageLoader.ReportProgress(0, new ProgressInfo(ProgressStep.Before, message));

                string url = string.Format("http://{0}.tumblr.com/page/{1}", tumblrId, page);
                var html = web.DownloadString(url);
                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(html);
                var nodes = document.DocumentNode.SelectNodes("//img");

                int imageCountInPage = 0;
                foreach (var node in nodes)
                {
                    var src = node.GetAttributeValue("src", null);

                    if (src == null || src.EndsWith(".jpg") == false)
                        continue;

                    Srcs.Add(src);
                    imageCountInPage++;
                }

#if DEBUG
                if (page == 3)
                    break;
#endif

                if (imageCountInPage == 0)
                    break;

                message = string.Format("총 {0:N0} 개의 이미지를 발견했습니다.", Srcs.Count);
                bgwPageLoader.ReportProgress(0, new ProgressInfo(ProgressStep.After, message));

                page++;
            }
        }

        private void bgwPageLoader_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgressInfo info = (ProgressInfo) e.UserState;

            if (info.ProgressStep == ProgressStep.Before)
                lblStatus1.Text = info.Message;
            else if (info.ProgressStep == ProgressStep.After)
                lblStatus2.Text = info.Message;
            else
                throw new NotImplementedException("PageLoadingForm.bgwPageLoader_ProgressChanged");
        }

        private void bgwPageLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DialogResult = DialogResult.OK;
            Close();
        }

        private class ProgressInfo
        {
            public ProgressInfo(ProgressStep progressStep, string message)
            {
                ProgressStep = progressStep;
                Message = message;
            }

            public ProgressStep ProgressStep { get; private set; }
            public string Message { get; private set; }
        }

        private enum ProgressStep
        {
            Before,
            After
        }
    }
}